#include "PhoenixInitializer.hpp"
#include "RenderingProcesser.hpp"

#include <cstdlib>

namespace phx
{

static bool glfwInitialized = false;

class PhoenixInitializer
{
public:
	PhoenixInitializer();
	void mainLoop(bool closeWhenWindowsClose);
	void leaveMainLoop();
private:
	static void terminate();
	static void init();
	bool mProcessing;
	bool mCloseWhenWindowsClose;
};

}

static phx::PhoenixInitializer PHX_INIT;

namespace phx
{

PhoenixInitializer::PhoenixInitializer() : 
	mProcessing(false),
	mCloseWhenWindowsClose(true)
{
	PhoenixInitializer::init();
}

void PhoenixInitializer::mainLoop(bool closeWhenWindowsClose)
{
	mCloseWhenWindowsClose = closeWhenWindowsClose;

	mProcessing = true;
	while( mProcessing && (!mCloseWhenWindowsClose || (mCloseWhenWindowsClose && RenderingProcesser::getInstance().mWindows.size() > 0)) )
	{
		RenderingProcesser::getInstance().process();
	}
	RenderingProcesser::getInstance().destroy();
}

void PhoenixInitializer::leaveMainLoop()
{
	mProcessing = false;
}

void PhoenixInitializer::terminate()
{
	glfwTerminate();
}

void PhoenixInitializer::init()
{
	if(!glfwInitialized)
	{
		glfwInit();
		atexit(terminate);
		glfwInitialized = true;
	}
}

void mainLoop(bool closeWhenWindowsClose)
{
	PHX_INIT.mainLoop(closeWhenWindowsClose);
}

void leaveMainLoop()
{
	PHX_INIT.leaveMainLoop();
}

}